const { userManageModel } = require('../models/o_userModel');
const { sectionModel } = require('../models/o_sectionModel');


// 按条件搜索 当条件为空加载全部
async function searchUsers(req, res, next) {
    // console.log(req.query);
    const { type,value, page } = req.query;
    // 分页查询
    const findUsers = await userManageModel
        .find({ [type]:{ $regex:value, $options:'$i' } })
        .limit(req.query.limit - 0)
        .skip((page - 1) * req.query.limit);
    // console.log(findUsers);
    // 计算总条数--------
    let total = await userManageModel.countDocuments({ [type]:{ $regex:value, $options:'$i' } } );
    if(findUsers.length > 0){
        res.send({
            message: '查询成功',
            code: 0,
            findUsers,
            total
        });
    } else {
        res.send({
            message: '查询失败没有这个人',
            code: 500
        });
    }
}

// 切换 用户状态------
async function changeState(req, res, next) {
    // console.log(req.query);
    const { _id , state} = req.query
    const result = await userManageModel.updateOne( { _id }, { state } );
    
}
//根据 最上层机构id查旗下的部门
async function getSection(req, res, next) {
    // console.log(req.params);
    const sections = await sectionModel.find({ pid: req.params._id})
    res.send(sections)
}

// 新增用户
async function createUser(req, res, next) {
    // console.log(req.body);
    const {user_name , user_uname , user_phone , section ,createTime} = req.body;
    const result = await userManageModel.create({ 
        name:  user_name,
        uname: user_uname,
        phone : user_phone,
        section,
        createTime,
        state:'启用'
    })
    if(result){
        res.send({
            message: '新增成功',
            code: 200,
        });
    }
}

// 删除用户
async function delUser(req, res, next) {
    console.log(req.body._id);
    const result = await userManageModel.deleteOne({ _id: req.body._id });
    if (result.n > 0) {
        res.send({
            code: 200,
            message: "删除成功"
        })
    }
}
// 删除多条用户
async function delUsers(req, res, next) {
    let usersId = JSON.parse(req.body.usersId);
    usersId.forEach(async item => {
        console.log(item);
        await userManageModel.deleteOne({ _id: item.id })
    });
}

//修改用户
async function updateUser(req, res, next) {
    console.log(req.body);
    const { _id , section , user_name , user_uname , user_phone } = req.body
    await userManageModel.updateOne({ _id }, { 
        name: user_name, 
        uname: user_uname,
        phone: user_phone,
        section
    });
}

module.exports = {
    searchUsers,
    changeState,
    getSection,
    createUser,
    delUser,
    delUsers,
    updateUser
}